//
//  RSChooseCityPickViewTwo.m
//  RSChooseCityPickerView
//
//  Created by thinkjoy on 16/9/30.
//  Copyright © 2016年 Thinkjoy_RS. All rights reserved.
//

#import "RSChooseCityPickViewTwo.h"

#define ScreenWidth  [[UIScreen mainScreen] bounds].size.width
#define ScreenHeight [[UIScreen mainScreen] bounds].size.height

#define kWinH [[UIScreen mainScreen] bounds].size.height
#define kWinW [[UIScreen mainScreen] bounds].size.width

////宽高比系数
#define WFACTOR (kWinW/320)
#define HFACTOR (kWinH/480)

#pragma mark - 日志开关
#ifdef DEBUG
#define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#define DLog(...)
#endif

@interface RSChooseCityPickViewTwo  ()<UIPickerViewDelegate, UIPickerViewDataSource>

@property(nonatomic,strong) UIView      * pickerViewCase;
@property(nonatomic,strong) UIButton    *bgButton;
@property   (nonatomic,strong)  UIPickerView    *   pickerView;

@end


@implementation RSChooseCityPickViewTwo
{
    NSArray   *_provinces;
    NSArray   *_citys;
    NSArray   *_areas;
    
    NSString  *_currentProvince;
    NSString  *_currentCity;
    NSString  *_currentDistrict;
    
}
//+ (instancetype)shareInstance
//{
//    static RSChooseCityPickerView *shareInstance = nil;
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        shareInstance = [[RSChooseCityPickerView alloc] init];
//    });
//
//    return shareInstance;
//}

- (instancetype)initWithTitle:(NSString *)title
{
    self    =   [super init];
    if (self)
    {
        self.frame  =   CGRectMake(0, 0, kWinW, kWinH);
        [[[UIApplication sharedApplication] keyWindow] addSubview:self];
        
        //pickerView出现时显示的行
        int oneColumn=18, twoColumn=3, threeColum=0;
        
        [self createDataWithProvinceCount:oneColumn cityConut:twoColumn districtCount:threeColum];  //需先设置数据源
        
        [self createViewWithTitle:(title==nil?@"请选择地点":title)];  //创建View
        
        [self pickerView:_pickerView didSelectRow:oneColumn inComponent:0];
        [self pickerView:_pickerView didSelectRow:twoColumn inComponent:1];
        [self pickerView:_pickerView didSelectRow:threeColum inComponent:2];
    }
    [self performSelector:@selector(show) withObject:self afterDelay:0.1];
    return self;
}

#pragma mark 出现弹框
- (void)show
{
    //发送通知,弹框出现,退出键盘
    //    [[NSNotificationCenter defaultCenter]postNotificationName:EndEdit object:self];
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    [UIView animateWithDuration:0.3 animations:^{
        _pickerViewCase.frame =    CGRectMake( 0, kWinH-kWinH/3, kWinW, kWinH/3);
        _bgButton.alpha =   0.3;
    } completion:^(BOOL finished) {
        
    }];
}
#pragma mark 消失
- (void)dismiss
{
    DLog(@"点击消失");
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        _pickerViewCase.frame =   CGRectMake( 0, kWinH, kWinW, kWinH/3);
        _bgButton.alpha =   0;
    } completion:^(BOOL finished) {
        [_pickerViewCase removeFromSuperview];
        [_bgButton removeFromSuperview];
        [weakSelf removeFromSuperview];
    }];
}
#pragma mark 消失并回调
- (void)dismissDatePicker:(UIButton *)butt
{
    DLog(@"点击消失");
    // 点击确定回调block
    if (self.chooseCityViewBlock) {
        self.chooseCityViewBlock(@{@"Province":_currentProvince,
                                   @"City":_currentCity,
                                   @"District":_currentDistrict});
    }
    if ([self respondsToSelector:@selector(chooseCityPickerView:getCityInfoDic:)]) {
        [self.delegate chooseCityPickerView:self getCityInfoDic:@{@"Province":_currentProvince,
                                                                  @"City":_currentCity,
                                                                  @"District":_currentDistrict}];
    }
    
    [self dismiss];
    
}
#pragma mark 初始化数据源
- (void)createDataWithProvinceCount:(int)oneColumn cityConut:(int)twoColumn districtCount:(int)threeColum
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"cityTwo" ofType:@"plist"];
    NSArray *data = [[NSArray alloc]initWithContentsOfFile:plistPath];
    
    _provinces = data;
    
    
    //默认选择的省份不能大于总数量
    NSAssert(oneColumn<_provinces.count, @"oneColumn=%d >= _provinces.count=%lu",oneColumn,(unsigned long)_provinces.count);
    // 第一个省分对应的全部市
    _citys = [[_provinces objectAtIndex:oneColumn] objectForKey:@"cities"];
    // 第一个省份
    _currentProvince = [[_provinces objectAtIndex:oneColumn] objectForKey:@"state"];
    
    //默认选择的市不能大于总数量
    NSAssert(twoColumn<_citys.count, @"twoColumn=%d >= _citys.count=%lu",twoColumn,(unsigned long)_citys.count);
    // 第一个省份对应的第一个市
    _currentCity = [[_citys objectAtIndex:twoColumn] objectForKey:@"city"];
    // 第一个省份对应的第一个市对应的第一个区
    _areas = [[_citys objectAtIndex:twoColumn] objectForKey:@"areas"];
    
    //默认选择的市不能大于总数量
    NSAssert(threeColum<_areas.count, @"threeColum=%d >= _areas.count=%lu",threeColum,(unsigned long)_areas.count);
    if (_areas.count > 0) {
        _currentDistrict = [_areas objectAtIndex:threeColum];
        //        [_pickerView selectRow:threeColum inComponent:3 animated:YES];
    } else {
        _currentDistrict = @"";
    }
    
}
#pragma mark 初始化控件
- (void)createViewWithTitle:(NSString *)title
{
    //半透明背景按钮
    _bgButton = [[UIButton alloc]init];
    [self addSubview:_bgButton];
    [_bgButton addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    _bgButton.tag   =   100;
    _bgButton.backgroundColor = [UIColor blackColor];
    _bgButton.alpha = 0;
    _bgButton.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    
    _pickerViewCase =   [[UIView alloc]initWithFrame:CGRectMake( 0, kWinH, kWinW, kWinH/3)];
    [self    addSubview:_pickerViewCase];
    _pickerViewCase.backgroundColor =   [UIColor whiteColor];
    
    UIView  * titleView =   [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWinW, 44)];
    titleView.backgroundColor  =   [UIColor whiteColor];
    [_pickerViewCase addSubview:titleView];
    
    UILabel * titleLabel    =   [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.pickerViewCase.frame.size.width, self.pickerViewCase.frame.size.height*7.0/43.0)];
    
    titleLabel.text =   title;
    titleLabel.textAlignment    =   NSTextAlignmentCenter;
    titleLabel.textColor    =   [UIColor lightGrayColor];
    [self.pickerViewCase    addSubview:titleLabel];
    
    UIButton    * commitButt    =   [UIButton buttonWithType:UIButtonTypeCustom];
    [titleView   addSubview:commitButt];
    commitButt.frame    =   CGRectMake(CGRectGetWidth(titleView.frame)-70, 0, 60, CGRectGetHeight(titleView.frame));
    
    [commitButt  setTitle:@"确定" forState:UIControlStateNormal];
    [commitButt setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
    commitButt.tag  =   200;
    [commitButt  addTarget:self action:@selector(dismissDatePicker:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton    * dismissButt    =   [UIButton buttonWithType:UIButtonTypeCustom];
    [titleView   addSubview:dismissButt];
    dismissButt.frame    =   CGRectMake(10, 0, 60, CGRectGetHeight(titleView.frame));
    
    //        [commitButt  setBackgroundColor:[UIColor colorWithHexString:NAV_TitleBgColor]];
    [dismissButt  setTitle:@"取消" forState:UIControlStateNormal];
    [dismissButt setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    dismissButt.tag  =   300;
    [dismissButt  addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    
    
    _pickerView    =   [[UIPickerView alloc]init];
    [_pickerViewCase addSubview:_pickerView];
    
    _pickerView.frame   =   CGRectMake(0, CGRectGetMaxY(titleView.frame), CGRectGetWidth(_pickerViewCase.frame), CGRectGetHeight(_pickerViewCase.frame)-CGRectGetHeight(titleView.frame));
    
    self.pickerView.delegate    =   self;
    self.pickerView.dataSource  =   self;
    [self.pickerViewCase    addSubview:self.pickerView];
}


#pragma mark - UIPickerViewDelegate

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

//设置列高
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return pickerView.frame.size.height/5.0;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            return [_provinces count];
            break;
        case 1:
            return [_citys count];
            break;
        case 2:
            
            return [_areas count];
            break;
            
        default:
            return 0;
            break;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (component)
    {
        case 0:
            return [[_provinces objectAtIndex:row] objectForKey:@"state"];
            break;
        case 1:
            return [[_citys objectAtIndex:row] objectForKey:@"city"];
            break;
        case 2:
            if ([_areas count] > 0) {
                return [_areas objectAtIndex:row];
                break;
            }
        default:
            return  @"";
            break;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    [pickerView selectRow:row inComponent:component animated:YES];
    
    switch (component)
    {
        case 0:
            
            _citys = [[_provinces objectAtIndex:row] objectForKey:@"cities"];
            [_pickerView selectRow:0 inComponent:1 animated:YES];
            [_pickerView reloadComponent:1];
            
            _areas = [[_citys objectAtIndex:0] objectForKey:@"areas"];
            [_pickerView selectRow:0 inComponent:2 animated:YES];
            [_pickerView reloadComponent:2];
            
            _currentProvince = [[_provinces objectAtIndex:row] objectForKey:@"state"];
            _currentCity = [[_citys objectAtIndex:0] objectForKey:@"city"];
            if ([_areas count] > 0) {
                _currentDistrict = [_areas objectAtIndex:0];
            } else{
                _currentDistrict = @"";
            }
            break;
            
        case 1:
            
            _areas = [[_citys objectAtIndex:row] objectForKey:@"areas"];
            [_pickerView selectRow:0 inComponent:2 animated:YES];
            [_pickerView reloadComponent:2];
            
            _currentCity = [[_citys objectAtIndex:row] objectForKey:@"city"];
            if ([_areas count] > 0) {
                _currentDistrict = [_areas objectAtIndex:0];
            } else {
                _currentDistrict = @"";
            }
            break;
            
        case 2:
            
            if ([_areas count] > 0) {
                _currentDistrict = [_areas objectAtIndex:row];
            } else{
                _currentDistrict = @"";
            }
            break;
            
        default:
            break;
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *pickerLabel = (UILabel *)view;
    if (!pickerLabel)
    {
        pickerLabel = [[UILabel alloc] init];
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setFont:[UIFont systemFontOfSize:16]];
    }
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    
    return pickerLabel;
}

@end
